package com.luyuan.framework.web.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.luyuan.common.core.domain.entity.WxappUser;
import com.luyuan.common.core.domain.model.WxappLoginUser;
import com.luyuan.common.enums.UserStatus;
import com.luyuan.common.exception.ServiceException;
import com.luyuan.common.utils.MessageUtils;
import com.luyuan.common.utils.StringUtils;
import com.luyuan.system.service.IWxappUserService;

/**
 * 微信小程序用户验证处理
 *
 * @author luyuan
 */
@Service("wxappUserDetailsService")
public class WxappUserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(WxappUserDetailsServiceImpl.class);

    @Autowired
    private IWxappUserService wxappUserService;

    @Override
    public UserDetails loadUserByUsername(String openid) throws UsernameNotFoundException {
        WxappUser user = wxappUserService.selectWxappUserByOpenid(openid);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", openid);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", openid);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", openid);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(WxappUser user) {
        return new WxappLoginUser(user.getUserId(), user, null);
    }
}